package com.xwdeshj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.entity.XwCityinfo;
import com.xwdeshj.repository.XwCityinfoRepository;
import com.xwdeshj.service.XwCityinfoService;
import com.xwdeshj.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Created by BKWJA on 2018/12/19.
 * 城市管理实现类
 */
@Service("xwCityinfoService")
@Slf4j
public class XwCityinfoServiceImpl implements XwCityinfoService {

    @Autowired
    private XwCityinfoRepository xwCityinfoRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private Sid sid;

    @Override
    public JSONObject getCityinfolist(Integer pageindex, Integer pagesize, String starttime,
                                      String endtime, String searchval, String searchkey,
                                      String sortfild, String sortway) {
        JSONObject result = new JSONObject();
        String sql = "select city_Id,city_encryptId,city_name,city_district_name,city_createtime,city_updatetime from xw_cityinfo ";
        StringBuffer sb = new StringBuffer();
        sb.append(" 1=1 ");
        if(!starttime.equals("")){
            starttime += " 00.00.01";
            endtime += " 23.59.59";
            sb.append(" and city_createtime >= '"+starttime+"' and city_createtime <= '"+ endtime + "' ");
        }
        //搜索内容查询
        if (!searchval.equals("")){
            sb.append(" and ( "+searchkey+" like '%" +searchval + "%' )");
        }
        //排序
        if (!sortfild.equals("")){
            sb.append(" order by "+sortfild+" " +sortway + " ");
        }
        try {
            sql = sql + " where " +sb.toString() + " limit "+ (pageindex-1)*pagesize + "," + pagesize;
            //分页SQL
            String sql2 = "select count(*) from xw_cityinfo where " + sb.toString();
            SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
            SqlRowSet rs2 = jdbcTemplate.queryForRowSet(sql2);
            result.put("status",0);
            result.put("msg","ok");
            while (rs2.next()){
                Integer count = rs2.getInt(1);
                result.put("recordcount",count);
                if (count%pagesize == 0){
                    result.put("pagecount",count/pagesize);
                }else {
                    result.put("pagecount",count/pagesize + 1);
                }
            }
            JSONArray jsonArray = new JSONArray();
            while (rs.next()){
                JSONObject object = new JSONObject();
                object.put("city_Id",rs.getString("city_Id"));
                object.put("city_encryptId",rs.getString("city_encryptId"));
                object.put("city_name",rs.getString("city_name"));
                object.put("city_district_name", rs.getString("city_district_name"));
                object.put("city_updatetime",DateUtil.DateToString(rs.getDate("city_updatetime")));
                object.put("city_createtime",DateUtil.DateToString(rs.getDate("city_createtime")));
                jsonArray.add(object);
            }
            result.put("list",jsonArray);
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","接口出现错误!");
        }
        System.out.println("getCityinfolist:"+result.toString());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject updatecityinfo(String city_encryptId, String city_name, String city_district_name) {
        JSONObject result = new JSONObject();

        if(city_encryptId.equals("")){
            XwCityinfo city = new XwCityinfo();
            city.setCityEncryptid(sid.nextShort());
            city.setCityName(city_name);
            city.setCityDistrictName(city_district_name);
            city.setCityUpdatetime(new Date());
            city.setCityCreatetime(new Date());
            try {
                xwCityinfoRepository.save(city);
                result.put("status",0);
                result.put("msg","ok");
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg",e);
            }
        }else {
            XwCityinfo cityinfo = xwCityinfoRepository.findByCityEncryptid(city_encryptId);

            if (cityinfo != null){
                cityinfo.setCityName(city_name);
                cityinfo.setCityDistrictName(city_district_name);
                cityinfo.setCityUpdatetime(new Date());
                try {
                    xwCityinfoRepository.save(cityinfo);
                    result.put("status",0);
                    result.put("msg","ok");
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("status",500);
                    result.put("msg",e);
                }
            }else {
                result.put("status",500);
                result.put("msg","该记录不存在！");
            }

        }
        System.out.println("updatecityinfo:"+result.toString());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject delcityinfo(String city_encryptId) {
        JSONObject result = new JSONObject();
        if(!"".equals(city_encryptId) && city_encryptId != null){
            try {
                if(city_encryptId.indexOf(",") == -1){
                    //单个删除
                    xwCityinfoRepository.deleteByCityEncryptid(city_encryptId);
                }else {
                    //批量删除
                    String[] tids = city_encryptId.split(",");
                    for (int i = 0; i < tids.length; i++) {
                        xwCityinfoRepository.deleteByCityEncryptid(tids[i]);
                    }
                }
                result.put("status",0);
                result.put("msg","ok");
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg",e);
            }

        }else {
            result.put("status",500);
            result.put("msg","city_encryptId不能为空！");
        }
        System.out.println("delcityinfo："+result);
        return result;
    }
}
